<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！ | 程序员小航</title><meta name="keywords" content="源码笔记,JDK"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="在看完 ReentrantLock 之后，在高并发场景下 ReentrantLock 已经足够使用，但是因为 ReentrantLock 是独占锁，同时只有一个线程可以获取该锁，而很多应用场景都是读多写少，这时候使用 ReentrantLock 就不太合适了。读多写少的场景该如何使用？在 JUC 包下同样提供了读写锁 ReentrantReadWriteLock 来应对读多写少的场景。">
<meta property="og:type" content="article">
<meta property="og:title" content="【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！">
<meta property="og:url" content="https://liuzhihang.com/2020/07/27/source-code-reentrant-read-write-lock.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="在看完 ReentrantLock 之后，在高并发场景下 ReentrantLock 已经足够使用，但是因为 ReentrantLock 是独占锁，同时只有一个线程可以获取该锁，而很多应用场景都是读多写少，这时候使用 ReentrantLock 就不太合适了。读多写少的场景该如何使用？在 JUC 包下同样提供了读写锁 ReentrantReadWriteLock 来应对读多写少的场景。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1ZuPsX.png">
<meta property="article:published_time" content="2020-07-27T15:50:00.000Z">
<meta property="article:modified_time" content="2020-12-27T09:23:14.595Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="源码笔记">
<meta property="article:tag" content="JDK">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1ZuPsX.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2020/07/27/source-code-reentrant-read-write-lock"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-27 17:23:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1ZuPsX.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-07-27T15:50:00.000Z" title="发表于 2020-07-27 23:50:00">2020-07-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-27T09:23:14.595Z" title="更新于 2020-12-27 17:23:14">2020-12-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/JDK/">JDK</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【JDK源码笔记】- 快进来！花几分钟看一下 ReentrantReadWriteLock 的原理！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/07/27/source-code-reentrant-read-write-lock.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p><strong>前言</strong></p>
<br>

<p>在看完 ReentrantLock 之后，在高并发场景下 ReentrantLock 已经足够使用，但是因为 ReentrantLock 是独占锁，同时只有一个线程可以获取该锁，而很多应用场景都是读多写少，这时候使用 ReentrantLock 就不太合适了。读多写少的场景该如何使用？在 JUC 包下同样提供了读写锁 ReentrantReadWriteLock 来应对读多写少的场景。</p>
</blockquote>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>支持类似 ReentrantLock 语义的 ReadWriteLock 的实现。</p>
<p>具有以下属性：</p>
<ul>
<li><strong>获取顺序</strong></li>
</ul>
<p>此类不会将读取优先或写入优先强加给锁访问的排序。但是，它确实支持可选的<em>公平</em> 策略。</p>
<p>支持<strong>公平模式</strong>和<strong>非公平模式</strong>，默认为<strong>非公平模式</strong>。</p>
<ul>
<li><strong>重入</strong></li>
</ul>
<p>允许 reader 和 writer 按照 <code>ReentrantLock</code> 的样式重新获取读锁或写锁。在写线程释放持有的所有写锁后，reader 才允许重入使用它们。此外，writer 可以获取读锁，但反过来则不成立。</p>
<ul>
<li><strong>锁降级</strong></li>
</ul>
<p>重入还允许从写锁降级为读锁，通过先获取写锁，然后获取读锁，最后释放写锁的方式降级。但是，从读锁升级到写锁是<strong>不可能的</strong>。</p>
<ul>
<li><strong>锁获取的中断</strong></li>
</ul>
<p>读锁和写锁都支持锁获取期间的中断。</p>
<ul>
<li><strong><code>Condition</code> 支持</strong></li>
</ul>
<p>写锁提供了一个 <code>Condition</code> 实现，对于写锁来说，该实现的方式与 <code>ReentrantLock.newCondition()</code> 提供的 <code>Condition</code> 实现对 <code>ReentrantLock</code> 所做的行为相同。当然，此 <code>Condition</code> 只能用于写锁。读锁不支持 <code>Condition</code>。</p>
<ul>
<li><strong>监测</strong></li>
</ul>
<p>此类支持一些确定是保持锁还是争用锁的方法。这些方法设计用于监视系统状态，而不是同步控制。</p>
<p>锁最多支持 65535 个递归写锁和 65535 个读锁</p>
<p>以上为 <em>Java Api 官方文档</em><sup>[1]</sup> 的解释，总结一下内容如下：</p>
<ol>
<li>支持非公平和公平模式，默认为非公平模式。</li>
<li>支持重入，读锁可以重入获取读锁，写锁可以重入获取写锁，写锁可以获取读锁，读锁不可以获取写锁。</li>
<li>锁可以降级，从写锁降级为读锁，但是不可能从读锁升级到写锁。</li>
</ol>
<h4 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h4><pre><code class="java">class CachedData &#123;
    Object data;
    volatile boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void processCachedData() &#123;
        // 读锁加锁
        rwl.readLock().lock();
        if (!cacheValid) &#123;
            // 获取写锁之前必须释放读锁
            rwl.readLock().unlock();
            // 写锁加锁
            rwl.writeLock().lock();
            try &#123;
                // 重新检查状态，因为另一个线程可能
                // 在执行操作之前获取了写锁定并更改了状态
                if (!cacheValid) &#123;
                    data = ...
                    cacheValid = true;
                &#125;
                // 通过在释放写锁之前获取读锁来降级
                rwl.readLock().lock();
            &#125; finally &#123;
                rwl.writeLock().unlock(); // Unlock write, still hold read
            &#125;
        &#125;

        try &#123;
            use(data);
        &#125; finally &#123;
            rwl.readLock().unlock();
        &#125;
    &#125;
&#125;</code></pre>
<p>上面只是官方文档提供的一个 demo。</p>
<h4 id="问题疑问"><a href="#问题疑问" class="headerlink" title="问题疑问"></a>问题疑问</h4><ol>
<li>在 ReentrantReadWriteLock 中 state 代表什么？</li>
<li>线程获取锁的流程是怎么样的？</li>
<li>读锁和写锁的可重入性是如何实现的？</li>
<li>当前线程获取锁失败，被阻塞的后续操作是什么？</li>
<li>锁降级是怎么降级的？</li>
</ol>
<h3 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h3><h4 id="代码结构"><a href="#代码结构" class="headerlink" title="代码结构"></a>代码结构</h4><p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-uml-SQCZqu.png" alt="ReentrantReadWriteLock-uml-SQCZqu"></p>
<pre><code class="java">public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable &#123;
    private static final long serialVersionUID = -6992448646407690164L;
    /** 提供读锁的内部类 */
    private final ReentrantReadWriteLock.ReadLock readerLock;
    /** 提供写锁的内部类 */
    private final ReentrantReadWriteLock.WriteLock writerLock;
    /** 执行所有同步机制 */
    final Sync sync;

&#125;</code></pre>
<h4 id="state"><a href="#state" class="headerlink" title="state"></a>state</h4><p>之前在阅读 ReentrantLock 源码的时候 state 代表了锁的状态，0 表示没有线程持有锁，大于 1 表示已经有线程持有锁及其重入的次数。而在 ReentrantReadWriteLock 是读写锁，那就需要保存<strong>读锁</strong>和<strong>写锁</strong>两种状态的，那是怎么样表示的呢？</p>
<p>在 ReentrantReadWriteLock 中同样存在一个 Sync 继承了 AbstractQueuedSynchronizer，也是 FairSync、NonfairSync 的父类。内部定义了 state 的一些操作。</p>
<pre><code class="java">abstract static class Sync extends AbstractQueuedSynchronizer &#123;
    private static final long serialVersionUID = 6317671515068378041L;
    // 移位数
    static final int SHARED_SHIFT   = 16;
    // 单位
    static final int SHARED_UNIT    = (1 &lt;&lt; SHARED_SHIFT);
    // 最大数量 1 &lt;&lt; 16 -&gt; 65536
    static final int MAX_COUNT      = (1 &lt;&lt; SHARED_SHIFT) - 1;
    // 计算独占数使用 1 &lt;&lt; 16 -&gt; 65536
    static final int EXCLUSIVE_MASK = (1 &lt;&lt; SHARED_SHIFT) - 1;

    // 返回共享保留数
    static int sharedCount(int c)    &#123; return c &gt;&gt;&gt; SHARED_SHIFT; &#125;
    // 返回独占保留数 
    static int exclusiveCount(int c) &#123; return c &amp; EXCLUSIVE_MASK; &#125;

&#125;
</code></pre>
<p>在 AQS 中定义 state 为 int 类型，而在 ReentrantReadWriteLock 中，将 state 的 高 16 位和低 16 位拆开表示读写锁。其中高 16 位表示读锁，低 16 位表示写锁。分别使用 sharedCount 和 exclusiveCount 方法获取读锁和写锁的当前状态。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-state-JusW2l.png" alt="ReentrantReadWriteLock-state-JusW2l"></p>
<p>下面分别从读锁和写锁的角度来看如何进行加锁和释放锁的？</p>
<h4 id="ReadLock-lock"><a href="#ReadLock-lock" class="headerlink" title="ReadLock.lock"></a>ReadLock.lock</h4><pre><code class="java">
public static class ReadLock 
    implements Lock, java.io.Serializable &#123;
    /**
     * 获取读取锁。
     * 如果写锁没有被另一个线程持有，则获取读锁并立即返回。
     * 如果写锁由另一个线程持有，则出于线程调度目的，
     * 当前线程将被禁用，并处于休眠状态，直到获取读锁为止。
     */
    public void lock() &#123;
        // 调用 AQS 获取共享资源
        sync.acquireShared(1);
    &#125;
&#125;</code></pre>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-AQS-Share-gTrD2e.png" alt="ReentrantReadWriteLock-AQS-Share-gTrD2e"></p>
<p>获取共享资源，这块使用的 AQS 的逻辑，其中 tryAcquireShared(arg) 是在 ReentrantReadWriteLock.Sync 中实现的。并且 AQS 中有规定，tryAcquireShared 分为三种返回值：</p>
<ol>
<li>小于 0: 表示失败；</li>
<li>等于 0: 表示共享模式获取资源成功，但后续的节点不能以共享模式获取成功; </li>
<li>大于 0: 表示共享模式获取资源成功，后续节点在共享模式获取也可能会成功，在这种情况下，后续等待线程必须检查可用性。</li>
</ol>
<pre><code class="java">abstract static class Sync extends AbstractQueuedSynchronizer &#123;
    protected final int tryAcquireShared(int unused) &#123;

        Thread current = Thread.currentThread();
        // 获取 state 值
        int c = getState();
        // 独占计数不为 0 且 不是当前线程， 说明已经有写锁
        if (exclusiveCount(c) != 0 &amp;&amp; getExclusiveOwnerThread() != current)
            return -1;
        // 获取共享计数（读锁计数）
        int r = sharedCount(c);
        // 不需要阻塞读锁 &amp;&amp; 共享计数小于最大值 &amp;&amp; state 更新成功
        if (!readerShouldBlock() &amp;&amp; r &lt; MAX_COUNT &amp;&amp;
            compareAndSetState(c, c + SHARED_UNIT)) &#123;
            if (r == 0) &#123;
                // 当前读锁计数为 0
                // firstReader是获得读锁的第一个线程
                // firstReaderHoldCount是firstReader的保持计数
                firstReader = current;
                firstReaderHoldCount = 1;
            &#125; else if (firstReader == current) &#123;
                // 读锁重入
                firstReaderHoldCount++;
            &#125; else &#123;
                // 当前缓存计数
                HoldCounter rh = cachedHoldCounter;
                // 当前线程没有计数 或者 没有创建计数器
                if (rh == null || rh.tid != getThreadId(current))
                    // 创建计数，基于 ThreadLocal
                    cachedHoldCounter = rh = readHolds.get();
                else if (rh.count == 0) 
                    readHolds.set(rh);
                // 计数累加
                rh.count++;
            &#125;
            return 1;
        &#125;
        // 完整地获取共享锁方法，作为tryAcquireShared方法因CAS获取锁失败后的处理。
        // 因为前面可能失败 CAS 失败， 队列策略失败等原因。
        return fullTryAcquireShared(current);
    &#125;
&#125;</code></pre>
<ol>
<li>先获取 state ，通过 exclusiveCount 方法获取到写锁的计数值，不为 0 且 不是当前线程， 说明已经有写锁。返回 -1 失败。</li>
<li>通过 sharedCount 获取读锁计数，判断是否需要阻塞以及是否超过上限后，使用 CAS 更新 读锁计数。</li>
<li>设置或更新 firstReader、firstReaderHoldCount、 cachedHoldCounter。</li>
<li>最后会进行完整的获取共享锁方法，作为之前获取失败的后续处理方法。</li>
</ol>
<p>firstReader：firstReader是获得读锁的第一个线程；<br>firstReaderHoldCount：firstReaderHoldCount是firstReader的保持计数。即获得读锁的第一个线程的重入次数。<br>cachedHoldCounter：最后一个获得读锁的线程获得读锁的重入次数。</p>
<pre><code class="java">final int fullTryAcquireShared(Thread current) &#123;

    HoldCounter rh = null;
    // 无限循环
    for (;;) &#123;
        int c = getState();
        // 是否有写锁
        if (exclusiveCount(c) != 0) &#123;
            // 有写锁，但是不是当前线程，直接返回失败
            if (getExclusiveOwnerThread() != current)
                return -1;
        &#125; else if (readerShouldBlock()) &#123;
            // 需要阻塞
            // 没有写锁，确保没有重新获取读锁
            if (firstReader == current) &#123;
                // assert firstReaderHoldCount &gt; 0;
            &#125; else &#123;
                // 当前线程的读锁计数 ThreadLocal 中
                if (rh == null) &#123;
                    rh = cachedHoldCounter;
                    if (rh == null || rh.tid != getThreadId(current)) &#123;
                        rh = readHolds.get();
                        // 计数结束，remove 掉
                        if (rh.count == 0)
                            readHolds.remove();
                    &#125;
                &#125;
                // 为 0 直接失败
                if (rh.count == 0)
                    return -1;
            &#125;
        &#125;
        // 到达上限 抛出异常
        if (sharedCount(c) == MAX_COUNT)
            throw new Error(&quot;Maximum lock count exceeded&quot;);
        // CAS 设置读锁
        if (compareAndSetState(c, c + SHARED_UNIT)) &#123;
            if (sharedCount(c) == 0) &#123;
                firstReader = current;
                firstReaderHoldCount = 1;
            &#125; else if (firstReader == current) &#123;
                firstReaderHoldCount++;
            &#125; else &#123;
                if (rh == null)
                    rh = cachedHoldCounter;
                if (rh == null || rh.tid != getThreadId(current))
                    rh = readHolds.get();
                else if (rh.count == 0)
                    readHolds.set(rh);
                rh.count++;
                cachedHoldCounter = rh; // cache for release
            &#125;
            return 1;
        &#125;
    &#125;
&#125;</code></pre>
<ol>
<li>首先会一直循环</li>
<li>有写锁，但是不是当前线程，直接返回失败。<strong>但是，有写锁，如果是当前线程，是会继续执行的。</strong></li>
<li>设置或更新 firstReader、firstReaderHoldCount、 cachedHoldCounter。</li>
</ol>
<p>当存在写锁（独占锁）时，方法会返回 -1 失败，后续会调用 AQS 的 doAcquireShared 方法，循环获取资源。doAcquireShared 方法会不断循环，尝试获取读锁，一旦获取到读锁，当前节点会立即唤醒后续节点，后续节点开始尝试获取读锁，依次传播。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1-rl0DjC.png" alt="ReentrantReadWriteLock-1-rl0DjC"></p>
<h4 id="ReadLock-unlock"><a href="#ReadLock-unlock" class="headerlink" title="ReadLock.unlock"></a>ReadLock.unlock</h4><pre><code class="java">public static class ReadLock 
    implements Lock, java.io.Serializable &#123;
    public void unlock() &#123;
        sync.releaseShared(1);
    &#125;
&#125;</code></pre>
<p>调用 AQS 的 releaseShared 释放共享资源方法。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReadLock-unlock-LE7vUH.png" alt="ReadLock-unlock-LE7vUH"></p>
<p>其中 tryReleaseShared 有 ReadLock 实现。</p>
<pre><code class="java">protected final boolean tryReleaseShared(int unused) &#123;
    Thread current = Thread.currentThread();
    if (firstReader == current) &#123;
        // 第一个线程是当前线程
        if (firstReaderHoldCount == 1)
            firstReader = null;
        else
            firstReaderHoldCount--;
    &#125; else &#123;
        // 第一个线程不是当前线程，更新自己的 ThreadLocal 里面的计数
        HoldCounter rh = cachedHoldCounter;
        if (rh == null || rh.tid != getThreadId(current))
            rh = readHolds.get();
        int count = rh.count;
        if (count &lt;= 1) &#123;
            readHolds.remove();
            if (count &lt;= 0)
                throw unmatchedUnlockException();
        &#125;
        --rh.count;
    &#125;
    // 循环
    for (;;) &#123;
        int c = getState();
        int nextc = c - SHARED_UNIT;
        // 使用 CAS 更新 state
        if (compareAndSetState(c, nextc))
            // 但是如果现在读和写锁都已释放，
            // 它可能允许等待的写程序继续进行。
            return nextc == 0;
    &#125;
&#125;</code></pre>
<ol>
<li>如果是第一个线程，直接更新技术，不是则更新自己 ThreadLocal 里面保存的计数。</li>
<li>循环，使用 CAS 更新 state 的值。</li>
<li>如果 state 更新后的值为 0，说明没有线程持有读锁或者写锁了。</li>
<li>当 state 为 0，此时会调用 AQS 的 doReleaseShared 方法。此时队列如果有写锁，那就会被写锁获取的锁。</li>
</ol>
<h4 id="WriteLock-lock"><a href="#WriteLock-lock" class="headerlink" title="WriteLock.lock"></a>WriteLock.lock</h4><pre><code class="java">public static class WriteLock 
    implements Lock, java.io.Serializable &#123;
    /**
     * 获取写入锁。
     * 如果没有其他线程持有读锁或写锁，会直接返回，并将写锁计数设置为1。
     * 如果当前线程持有写锁，则将写锁计数 +1，然后返回。
     * 如果锁正在被其他线程持有，则当前线程用于线程调度目的，
     * 当前线程将被禁用，并处于休眠状态，直到获取读锁并将写锁计数设置为1。
     */
    public void lock() &#123;
        sync.acquire(1);
    &#125;
&#125;
</code></pre>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/WriteLock.lock-wBuvUA.png" alt="WriteLock.lock-wBuvUA"></p>
<p>tryAcquire 方法由 Write 自己实现，方式和 ReentrantLock 类似。</p>
<pre><code class="java">protected final boolean tryAcquire(int acquires) &#123;

    // 如果读锁计数为非零或写锁计数为非零，并且所有者是另一个线程，则失败。
    // 如果计数饱和，则失败。只有在count不为零时，才可能发生这种情况。
    // 否则，如果该线程是可重入获取或队列策略允许的话，则有资格进行锁定。
    // 如果是这样，请更新状态并设置所有者。
    Thread current = Thread.currentThread();
    int c = getState();
    // 写锁计数
    int w = exclusiveCount(c);
    // c ！= 0 说明有有线程获取锁了
    if (c != 0) &#123;
        // (Note: if c != 0 and w == 0 then shared count != 0)
        // 判断是不是自己，不是自己 返回 false
        if (w == 0 || current != getExclusiveOwnerThread())
            return false;
        // 判断有没有超过上限
        if (w + exclusiveCount(acquires) &gt; MAX_COUNT)
            throw new Error(&quot;Maximum lock count exceeded&quot;);
        // 重入
        setState(c + acquires);
        return true;
    &#125;
    // 不需要阻塞，或者 CAS 更新 state 失败
    if (writerShouldBlock() || !compareAndSetState(c, c + acquires))
        return false;
    setExclusiveOwnerThread(current);
    return true;
&#125;</code></pre>
<ol>
<li>获取 state ， 如果 state 不为 0 则判断是否为当前线程重入获取。</li>
<li>state 为 0 ，则当前线程 CAS 更新 state，获取锁。</li>
<li>更新成功之后绑定当前线程。</li>
<li>如果失败会继续调用 AQS 的 acquireQueued，将当前阻塞放在 AQS 队列中。AQS 会不断循环，等待上一个锁释放后，尝试获得锁。</li>
</ol>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-2-mQAgGL.png" alt="ReentrantReadWriteLock-2-mQAgGL"></p>
<h4 id="WriteLock-unlock"><a href="#WriteLock-unlock" class="headerlink" title="WriteLock.unlock"></a>WriteLock.unlock</h4><pre><code class="java">public static class WriteLock 
    implements Lock, java.io.Serializable &#123;
    // 如果当前线程是此锁的持有者，则保持计数递减。 
    // 如果保持现在的计数为零，则解除锁定。 
    // 如果当前线程不是此锁的持有者则IllegalMonitorStateException异常。
    public void unlock() &#123;
        sync.release(1);
    &#125;
&#125;</code></pre>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/Write-unlock-bwHAcw.png" alt="Write-unlock-bwHAcw"></p>
<p>同样这块代码是使用 AQS 的逻辑，tryRelease 部分由 WriteLock 自己实现。</p>
<pre><code class="java">protected final boolean tryRelease(int releases) &#123;
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    int nextc = getState() - releases;
    boolean free = exclusiveCount(nextc) == 0;
    if (free)
        setExclusiveOwnerThread(null);
    setState(nextc);
    return free;
&#125;</code></pre>
<ol>
<li>如果是当前线程重入，扣减重入次数。</li>
<li>扣减后如果为 0，则设置锁持有线程为 null，更新 state 值。AQS 会唤醒后续节点获取锁。</li>
</ol>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><h4 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h4><p><strong>Q：</strong>在 ReentrantReadWriteLock 中 state 代表什么？</p>
<p><strong>A：</strong>state 代表锁的状态。state 为 0 ，没有线程持有锁，state 的高 16 为代表读锁状态，低 16 为代表写锁状态。通过位运算可以获取读写锁的实际值。</p>
<p><strong>Q：</strong>线程获取锁的流程是怎么样的？</p>
<p><strong>A：</strong>可以参考上面的源码笔记，以及后面的流程图。</p>
<p><strong>Q：</strong>读锁和写锁的可重入性是如何实现的？</p>
<p><strong>A：</strong>在加锁的时候，判断是否为当前线程，如果是当前线程，则直接累加计数。值得注意的是：读锁重入计数使用的 ThreadLocal 在线程中缓存计数，而写锁则直接用的 state 进行累加（其实和 state 低 16 位进行累加一样）。</p>
<p><strong>Q：</strong>当前线程获取锁失败，被阻塞的后续操作是什么？</p>
<p><strong>A：</strong>获取失败，会放到 AQS 等待队列中，在队列中不断循环，监视前一个节点是否为 head ，是的话，会重新尝试获取锁。</p>
<p><strong>Q：</strong>锁降级是怎么降级的？</p>
<p><strong>A：</strong> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/write-to-read-koAuqm.png" alt="write-to-read-koAuqm"><br>如图，在圈出部分 fullTryAcquireShared 代码中，可以看出来，在获取读锁的时候，如果当前线程持有写锁，是可以获取读锁的。这块就是指锁降级，比如线程 A 获取到了写锁，当线程 A 执行完毕时，它需要获取当前数据，假设不支持锁降级，就会导致 A 释放写锁，然后再次请求读锁。而在这中间是有可能被其他阻塞的线程获取到写锁的。从而导致线程 A 在一次执行过程中数据不一致。</p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><ol>
<li>ReentrantReadWriteLock 读写锁，内部实现是 ReadLock 读锁 和 WriteLock 写锁。读锁，允许共享；写锁，是独占锁。</li>
<li>读写锁都支持重入，读锁的重入次数记录在线程维护的 ThreadLocal 中，写锁维护在 state 上（低 16 位）。</li>
<li>支持锁降级，从写锁降级为读锁，防止脏读。</li>
<li>ReadLock 和 WriteLock 都是通过 AQS 来实现的。获取锁失败后会放到 AQS 等待队列中，后续不断尝试获取锁。区别在读锁只有存在写锁的时候才放到等待队列，而写锁是只要存在非当前线程锁（无论写锁还是读锁）都会放到等待队列。<img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/read-write-different-gzNdCo.png" alt="read-write-different-gzNdCo"></li>
<li>通过源码分析，可以得出读写锁适合在<strong>读多写少</strong>的场景中使用。</li>
</ol>
<h4 id="相关资料"><a href="#相关资料" class="headerlink" title="相关资料"></a>相关资料</h4><p>[1] Java Api：<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/8/docs/api/overview-summary.html">https://docs.oracle.com/javase/8/docs/api/overview-summary.html</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2020/07/27/source-code-reentrant-read-write-lock.html">https://liuzhihang.com/2020/07/27/source-code-reentrant-read-write-lock.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><a class="post-meta__tags" href="/tags/JDK/">JDK</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantReadWriteLock-1ZuPsX.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/07/29/tool-book-copy-as-json.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/copy-as-json-JBXqqv.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【工具册】- IDEA 插件找不到？看这里！那就自己敲一个！</div></div></a></div><div class="next-post pull-right"><a href="/2020/07/25/source-code-reentrant-lock.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ReentrantLock-RljCvj.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【JDK源码笔记】- 不能再被问住了！ReentrantLock 源码、画图一起看一看！</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/12/source-code-aqs.html" title="【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/aqs-uhgQnu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-12</div><div class="title">【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)</div></div></a></div><div><a href="/2020/09/27/source-code-arrayblockingqueue.html" title="【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ArrayBlockingQueue-cover-ESuNmo.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-27</div><div class="title">【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue</div></div></a></div><div><a href="/2020/06/12/source-code-cas.html" title="【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">基本使用</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E7%96%91%E9%97%AE"><span class="toc-text">问题疑问</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-text">源码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%BB%93%E6%9E%84"><span class="toc-text">代码结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#state"><span class="toc-text">state</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReadLock-lock"><span class="toc-text">ReadLock.lock</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ReadLock-unlock"><span class="toc-text">ReadLock.unlock</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#WriteLock-lock"><span class="toc-text">WriteLock.lock</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#WriteLock-unlock"><span class="toc-text">WriteLock.unlock</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98"><span class="toc-text">问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E8%B5%84%E6%96%99"><span class="toc-text">相关资料</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: 'abd9465954141b99ad4fe32e6f1e6319',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>